package com.njlime.core.sdk.wechat.mass;

import com.alibaba.fastjson.JSONObject;
import com.njlime.cms.util.UrlUtil;
import com.njlime.core.exception.BusinessException;
import com.njlime.core.sdk.wechat.WeChatUtil;
import com.njlime.core.sdk.wechat.jsapi.AccessToken;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.security.util.UserUtils;
import com.njlime.sys.service.UnitService;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpMaterialServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 群发
 *
 * @author
 * @date 2016年1月13日15:09:29
 */
public class Mass {
    static Logger logger = Logger.getLogger(WeChatUtil.class);

    public static WxMpService wxService;
    @Resource
    private UnitService unitService;

    public static WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();

    public static WxMpMaterialService wxMpMaterialService;

    /**
     * 群发文本
     *
     * @param tagId 标签id
     * @param text  内容
     * @return
     */
    public static int sendall(int tagId, int unitId, String text) {
        try {
            // 获取单位公共号信息信息
            UnitWxConfig config = UserUtils.getUnitConfig(unitId);
            if (config != null) {
                AccessToken token = WeChatUtil.getAccessToken(config.getApp_id(), config.getApp_secret());
                System.out.println(token.getToken());
                if (token != null) {
                    String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=" + token.getToken();
                    String data = "{\"filter\":{\"is_to_all\":false,\"tag_id\":" + tagId + "},\"text\":{\"content\":\"+text+\"}, \"msgtype\":\"text\"}";
                    JSONObject json = WeChatUtil.httpRequest(requestUrl, "POST", data);
                    System.out.println("sendall:" + data + "_____" + json.toJSONString());
                    if (json.get("errcode") != null) {
                        String errcode = json.get("errcode").toString();
                        return Integer.parseInt(errcode);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return -1;
    }

    /**
     * 群发图文
     *
     * @param tagId 标签id
     * @return
     */
    public static int sendallMpnews( int tagId, int unitId, String title, String url, String content, HttpServletRequest request) {
        try {
            UnitWxConfig wxConfig = UserUtils.getUnitConfig(unitId);
            if (wxConfig != null) {
                if (config.getAppId() == null || config.getAppId().equals(wxConfig.getApp_id())) {
                    config.setAppId(wxConfig.getApp_id());
                    config.setSecret(wxConfig.getApp_secret()); // 设置微信公众号的app corpSecret*/

                    wxService = new WxMpServiceImpl();
                    wxService.setWxMpConfigStorage(config);
                    wxMpMaterialService = new WxMpMaterialServiceImpl(wxService);
                }
            } else {
                throw new BusinessException("请先设置微信信息");
            }
            // 获取单位公共号信息信息
            UnitWxConfig config = UserUtils.getUnitConfig(unitId);
            AccessToken token = WeChatUtil.getAccessToken(config.getApp_id(), config.getApp_secret());
            WxMpMaterial wxMaterial = new WxMpMaterial();
            File file = UrlUtil.url2File(url, "theme_1.jpg", request.getServletContext().getRealPath("/"));
            wxMaterial.setFile(file);
            wxMaterial.setName(title);
            WxMpMaterialUploadResult res = wxService.getMaterialService().materialFileUpload("image", wxMaterial);


            WxMpMaterialNews wxMpMaterialNewsSingle = new WxMpMaterialNews();
            WxMpMaterialNews.WxMpMaterialNewsArticle mpMaterialNewsArticleSingle =
                    new WxMpMaterialNews.WxMpMaterialNewsArticle();
            mpMaterialNewsArticleSingle.setAuthor(" ");
            mpMaterialNewsArticleSingle.setThumbMediaId(res.getMediaId());
            mpMaterialNewsArticleSingle.setTitle(title);
            mpMaterialNewsArticleSingle.setContent(content);
            mpMaterialNewsArticleSingle.setContentSourceUrl("");
            mpMaterialNewsArticleSingle.setShowCoverPic(true);
            mpMaterialNewsArticleSingle.setDigest("");
            wxMpMaterialNewsSingle.addArticle(mpMaterialNewsArticleSingle);
            WxMpMaterialUploadResult resSingle =
                    wxService.getMaterialService().materialNewsUpload(wxMpMaterialNewsSingle);


            if (config != null) {
                System.out.println(token.getToken());
                if (token != null) {
                    String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=" + token.getToken();
                     StringBuilder sb = new StringBuilder();

                    sb.append("{");
                    sb.append("\"filter\":{");
                    sb.append("\"is_to_all\":false,");
                    sb.append("\"tag_id\":"+tagId);
                    sb.append("},");
                    sb.append("\"mpnews\":{");
                    sb.append("\"media_id\":\"" + resSingle.getMediaId()+ "\"");
                    sb.append("},");
                    sb.append("\"msgtype\":\"mpnews\",");
                    sb.append("\"send_ignore_reprint\":0");
                    sb.append("}");

                    JSONObject json = WeChatUtil.httpRequest(requestUrl, "POST", sb.toString());
                    System.out.println("sendall2:" + sb.toString() + "_____" + json.toJSONString());
                    if (json.get("errcode") != null) {
                        String errcode = json.get("errcode").toString();
                        return Integer.parseInt(errcode);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return -1;
    }

}
